package br.com.servlet.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.model.Conto;
import br.com.model.Ponto;
import br.com.model.dao.DAO;
import br.com.model.dao.DAOFactory;
import br.com.model.dao.PontoDAO;
import br.com.util.JsonGenerator;
import br.com.util.Retorno;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Controller
public class ServicoController 
{
	@RequestMapping("/gson-contos")
	public void contos( Integer npag, HttpServletResponse response )
	{
		response.setContentType( "application/json" );
		
		try 
		{
			Gson g = new GsonBuilder( ).excludeFieldsWithoutExposeAnnotation( ).create( );
			
			String json = "";
			
			try
			{
				if( npag == null || npag < 0 )
				{
					npag = 0;
				}
				
				DAO dao = DAOFactory.infDao( );
				
				List<Conto> busca = dao.busca( "select c from Conto c",  npag * 50, 50, Conto.class );
				
				json = g.toJson( busca );
				
				dao.close( );
			}
			catch( Exception e )
			{
				e.printStackTrace( );
			}
			
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
	
	@RequestMapping("/gson-pontos")
	public void pontos( Integer idConto, HttpServletResponse response )
	{
		response.setContentType( "application/json" );
		
		try 
		{
			Gson g = new GsonBuilder( ).excludeFieldsWithoutExposeAnnotation( ).create( );
			
			String json = "";
			
			try
			{
				DAO dao = DAOFactory.infDao( );
				
				List<Ponto> pontos = dao.busca( "select p from Ponto p where p.conto.IdConto = " + idConto, Ponto.class );
				
				json = g.toJson( pontos );
				
				dao.close( );
			}
			catch( Exception e )
			{
				e.printStackTrace( );
			}
			
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
	
	@RequestMapping("/add-ponto")
	public void addPonto( Long idconto, Long idusr, Integer pontos, HttpServletResponse response )
	{
		response.setContentType( "application/json" );
		
		try
		{
			String json = "";
			
			try
			{
				PontoDAO dao = DAOFactory.infPontoDao( );
				
				Retorno ret = dao.addPonto( idusr, idconto, pontos );
				
				if( ret.isOk( ) )
				{
					json = JsonGenerator.newJsonOk( "menssagem", "OK" );
				}
				else
				{
					json = JsonGenerator.newJsonError( ret.getMenssagem( ) );
				}
				
				dao.close( );
			}
			catch( Exception e )
			{
				e.printStackTrace( );
			}
			
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
}